package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.client.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.PageResult;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.ISearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ahcfl
 * @Date: 2021年07月30日 10:58
 * @Description:
 */
@Service
public class SearchService implements ISearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ItemClient itemClient;

    /*基本查询*/
    @Override
    public PageResult getList(RequestParams params) {
        SearchResponse response = null;
        try {
            //PageResult pageResult = new PageResult();
            // 准备请求参数
            SearchRequest request = new SearchRequest("item");

            // track_total_hits 设置为false禁用跟踪匹配查询的总查询次数
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.trackTotalHits(true);
            request.source(sourceBuilder);

            // 1 组合 全文 精准 范围  算分  查询
            boolQueryBuild(params, request);

            // 2 分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            // 3 排序查询
            sortQuery(params, request);

            // 4 高亮显示
            request.source().highlighter(new HighlightBuilder()
                    .field("name")
                    .requireFieldMatch(false));


            // 客户端发生请求
            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("基本擦查询异常~~~", e);
        }

        return parseResponse(response);
    }

    /*解析响应结果*/
    public PageResult parseResponse(SearchResponse response) {
        // 解析响应
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        List<ItemDoc> itemDocs = new ArrayList<>(hits.length);
        // 遍历 获取 结果 添加到list
        if (hits.length > 0) {
            for (SearchHit hit : hits) {
                // 获取source   反序列化成对象
                String hitJson = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(hitJson, ItemDoc.class);
                // 处理高亮
                Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields();
                if (highlightFieldMap != null && !highlightFieldMap.isEmpty()) {
                    HighlightField highlightField = highlightFieldMap.get("name");
                    if (highlightField != null) {
                        String nameHigh = highlightField.getFragments()[0].toString();
                        itemDoc.setName(nameHigh);
                    }
                }

                // 放入集合
                itemDocs.add(itemDoc);
            }
        }
        //System.out.println("itemDocs = " + itemDocs);
        // 返回解析分页类
        return new PageResult(total, itemDocs);
    }

    /*DSL排序*/
    public void sortQuery(RequestParams params, SearchRequest request) {
        String sortBy = params.getSortBy();
        if ("default".equals(sortBy) && StringUtils.isNotBlank(sortBy)) {
            request.source().sort("_score", SortOrder.DESC);
        }
        // 销量降序 sold
        if (StringUtils.isNotBlank(sortBy)) {
            request.source().sort("sold", SortOrder.DESC);
        }
        // 价格升序 price
        if ("price".equals(sortBy) && StringUtils.isNotBlank(sortBy)) {
            request.source().sort("price", SortOrder.ASC);
        }
    }

    /*组合 全文 精准 范围  算分  查询*/
    public void boolQueryBuild(RequestParams params, SearchRequest request) {
        // 准备请求参数  组合查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1. 关键字搜索
        String key = params.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        // 2. 分类
        String category = params.getCategory();
        if (StringUtils.isNotBlank(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }

        // 3. 品牌
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }

        // 4. 价格
        Integer maxPrice = params.getMaxPrice();
        Integer minPrice = params.getMinPrice();
        if (maxPrice != null && minPrice != null) {
            maxPrice = maxPrice == 0 ? Integer.MAX_VALUE : maxPrice;
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lte(maxPrice));
        }

        // 算分函数查询
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
        );

        request.source().query(functionScoreQuery);
    }

    /*过滤聚合*/
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1.request
            SearchRequest request = new SearchRequest("item");
            // 2.DSL
            // 2.1query
            boolQueryBuild(params, request);
            // 2.2设置query size
            request.source().size(0);
            // 2.3聚合查询
            aggregationQuery(request);

            // 3.发出请求
            SearchResponse response = restHighLevelClient
                    .search(request, RequestOptions.DEFAULT);

            // 4. 解析聚合过滤结果
            Map<String, List<String>> aggsResultMap = new HashMap<>();

            Aggregations aggregations = response.getAggregations();

            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggsByName(aggregations, "brandAgg");
            aggsResultMap.put("brand", brandList);
            List<String> categoryList = getAggsByName(aggregations, "categoryAgg");
            aggsResultMap.put("category", categoryList);
            return aggsResultMap;
        } catch (IOException e) {
            throw new RuntimeException("过滤查询失败~~~", e);
        }
    }

    /*添加聚合参数*/
    public void aggregationQuery(SearchRequest request) {
        // Bucket（桶）：对文档数据分组，并统计每组数量
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")   // 聚合的类型，按照品牌值聚合，所以选择term
                .field("brand")            // 品牌分桶
                .size(90));
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(90));
    }

    /*获取聚合后的key*/
    public List<String> getAggsByName(Aggregations aggregations, String aggName) {
        // 4.1 根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 获取 buckets{"key":"如家","doc_count":2}
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString(); // "key":"小米" "key":"手机"
            list.add(key);
        }
        return list;
    }

    /*自动补全*/
    @Override
    public List<String> getSuggestion(String key) {
        try {
            // request
            SearchRequest request = new SearchRequest("item");
            request.source().suggest(
                    new SuggestBuilder().addSuggestion(
                            "itemSuggest",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(key)
                                    .skipDuplicates(true)
                                    .size(10)
                    )
            );
            // 发起请求
            SearchResponse response = restHighLevelClient
                    .search(request, RequestOptions.DEFAULT);
            // 解析结果
            Suggest suggest = response.getSuggest();
            //System.out.println("suggest = " + suggest.toString());

            // 根据补全查询名称，获取补全结果
            // Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends
            // Suggest.Suggestion.Entry.Option>>
            CompletionSuggestion suggestions = suggest.getSuggestion("itemSuggest");
            // 获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            System.out.println("options = " + options);
            // 遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }

            return list;
        } catch (IOException e) {
            throw new RuntimeException("自动补全失败~~~", e);
        }
    }

    /*同步删除商品*/
    @Override
    public void deleteById(Long itemId) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest("item",itemId.toString());
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("同步删除失败~~~", e);
        }
    }

    /*同步增/改商品*/
    @Override
    public void saveById(Long itemId) {
        try {
            Item item = itemClient.queryItemById(itemId);
            ItemDoc itemDoc = new ItemDoc(item);
            IndexRequest request = new IndexRequest("item").id(itemId.toString()); // 新增或修改的商品id
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException("同步增/改失败~~~", e);
        }
    }
}
